#include "stdafx.h"
#include "thread/threadlocal.hpp"
#include "designpattern/singletonholder.hpp"
using namespace JHCPP::designpattern;
#include "thread/thread.hpp"

namespace JHCPP
{
	namespace thread
	{
		////////////////////////////////////////////
		//CTLSAbstractSlot
		////////////////////////////////////////////
		CTLSAbstractSlot::CTLSAbstractSlot()
		{
		}

		CTLSAbstractSlot::~CTLSAbstractSlot()
		{
		}

		////////////////////////////////////////////
		//CThreadLocalStorage
		////////////////////////////////////////////
		CThreadLocalStorage::CThreadLocalStorage()
		{
		}
	
		CThreadLocalStorage::~CThreadLocalStorage()
		{
			for (TLSMap::iterator it = m_mapAbsSlot.begin(); it != m_mapAbsSlot.end(); ++it)
			{
				delete it->second;	
			}
		}

		CTLSAbstractSlot*& CThreadLocalStorage::get(const void* key)
		{
			TLSMap::iterator it = m_mapAbsSlot.find(key);
			if (it == m_mapAbsSlot.end())
				return m_mapAbsSlot.insert(TLSMap::value_type(key, reinterpret_cast<CTLSAbstractSlot*>(0))).first->second;
			else
				return it->second;
		}


		static TSingletonHolder<CThreadLocalStorage> sh;
		
		CThreadLocalStorage& CThreadLocalStorage::current()
		{
			CThread* pThread = CThread::current();
			if (pThread)
			{
				return pThread->tls();
			}
			else
			{
				return *sh.get();
			}
		}

		void CThreadLocalStorage::clear()
		{
			CThread* pThread = CThread::current();
			if (pThread)
				pThread->clearTLS();
		}
	}//end of namespace thread
}//end of namespace JHCPP
